package org.example.Polls;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

public class CreatePollActivity extends Activity implements OnClickListener {
	// constants
	public static final String CREATE_POLL_EXTRA = "uVote.CreatePollActivity.pollId";
	private static final String TAG = "CreatePollActivity";
	
	// constants for return results
	private static final int ADD_PARTICIPANTS_RESULT = 1;
	private static final int ADD_ITEMS_RESULT = 2;
	
	static final int START_TIME_DIALOG_ID = 0;
	static final int START_DATE_DIALOG_ID = 1;
	static final int END_TIME_DIALOG_ID = 2;
	static final int END_DATE_DIALOG_ID = 3;
	
	// other member variables
	private DateFormat mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	private Date mStartDateTime;
	private Date mEndDateTime;
	private int mStartHour;
	private int mStartMinute;
	private int mEndHour;
	private int mEndMinute;
	private int mStartYear;
	private int mStartMonth;
	private int mStartDay;
	private int mEndYear;
	private int mEndMonth;
	private int mEndDay;
	
	// widgets containing data
	private EditText txtStartTimeAndDate;
	private EditText txtEndTimeAndDate;
	private CheckBox chkPublic;
	private CheckBox chkAnonymous;
	private CheckBox chkDynamic;
	private EditText txtTitle;
	
	private PollService pollService;
	
	// List of participants
	private ArrayList<String> participants = new ArrayList<String>();
	private ArrayList<String> items = new ArrayList<String>();
	
	public CreatePollActivity() {
		pollService = DefaultServiceFactory.getInstance().createPollService();
		
		Calendar c = Calendar.getInstance();
		mStartHour = c.get(Calendar.HOUR);
		mStartMinute = c.get(Calendar.MINUTE);
		mStartYear = c.get(Calendar.YEAR);
		mStartMonth = c.get(Calendar.MONTH);
		mStartDay = c.get(Calendar.DAY_OF_MONTH);
		mStartDateTime = c.getTime();
		
		// Default end date to one day after start date
		c.add(Calendar.DAY_OF_MONTH, 1);
		mEndHour = c.get(Calendar.HOUR);
		mEndMinute = c.get(Calendar.MINUTE);
		mEndYear = c.get(Calendar.YEAR);
		mEndMonth = c.get(Calendar.MONTH);
		mEndDay = c.get(Calendar.DAY_OF_MONTH);
		mEndDateTime = c.getTime();
	}

	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create_poll);
		
		
		Button addParticipants = (Button) findViewById(R.id.create_poll_add_button);
		Button addItems = (Button) findViewById(R.id.create_poll_add_item);
		Button submitPoll = (Button) findViewById(R.id.create_poll_submit_button);
		
		addParticipants.setOnClickListener(this);
		addItems.setOnClickListener(this);
		submitPoll.setOnClickListener(this);
		
		txtStartTimeAndDate = (EditText) findViewById(R.id.txtStartTimeAndDate);
		txtEndTimeAndDate = (EditText) findViewById(R.id.txtEndTimeAndDate);
		txtTitle = (EditText)findViewById(R.id.create_poll_question_input);
		chkPublic = (CheckBox)findViewById(R.id.create_poll_public_poll_check);
		chkAnonymous = (CheckBox)findViewById(R.id.create_poll_anon_poll_check);
		chkDynamic = (CheckBox)findViewById(R.id.create_poll_dyn_poll_check);
		
		// Initialize text fields with the default dates
		txtStartTimeAndDate.setText(mDateFormat.format(mStartDateTime));
		txtEndTimeAndDate.setText(mDateFormat.format(mEndDateTime));
		
		txtStartTimeAndDate.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View arg0, MotionEvent argl) {
				showDialog(START_DATE_DIALOG_ID);
				return true;
			}
		});
		
		txtEndTimeAndDate.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View arg0, MotionEvent argl) {
				showDialog(END_DATE_DIALOG_ID);
				return true;
			}
		});
	}
	
    @SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "onActivityResult: requestCode="+requestCode+" resultCode="+resultCode);
		List<String> retList = null;
		switch (requestCode) {
    		case ADD_PARTICIPANTS_RESULT:
        		if (resultCode != RESULT_OK)
        			return;
        		retList =  (List<String>)data.getExtras().getSerializable(AddParticipantsActivity.ADD_PARTICIPANTS_EXTRA);
        		participants = new ArrayList<String>(retList);
    			Log.i(TAG, "AddParticipantsActivity returned "+participants.size()+" participants");
    			break;
    		case ADD_ITEMS_RESULT:
        		if (resultCode != RESULT_OK)
        			return;
        		retList =  (List<String>)data.getExtras().getSerializable(AddItemsActivity.ADD_ITEMS_EXTRA);
        		items = new ArrayList<String>(retList);
    			Log.i(TAG, "AddItemsActivity returned "+items.size()+" items");
    			break;
    		default:
    			Log.w(TAG, "Unknown resultCode");
		}
	}

	public void onClick(View v) {
		Log.d(TAG, "entering onClick for Add Participants...");
		Intent intent = null;
		switch(v.getId()) {
		case R.id.create_poll_add_button:
			Log.d(TAG, "starting AddParticipantsActivity activity...");
			intent = new Intent(this, AddParticipantsActivity.class);
			intent.putExtra(AddParticipantsActivity.ADD_PARTICIPANTS_EXTRA, participants);
			startActivityForResult(intent, ADD_PARTICIPANTS_RESULT);
			break;
		case R.id.create_poll_add_item:
			Log.d(TAG, "starting AddItemsActivity activity...");
			intent = new Intent(this, AddItemsActivity.class);
			intent.putExtra(AddItemsActivity.ADD_ITEMS_EXTRA, items);
			startActivityForResult(intent, ADD_ITEMS_RESULT);
			break;
		case R.id.create_poll_submit_button:
			RequestContext ctxt = RequestContext.getContext();
    		Poll poll = new Poll();
    		poll.setAnonymous(chkAnonymous.isChecked());
    		poll.setPublc(chkPublic.isChecked());
    		poll.setDynamic(chkDynamic.isChecked());
    		poll.setTitle(txtTitle.getText().toString());
    		poll.setStartDate(mStartDateTime);
    		poll.setEndDate(mEndDateTime);
    		poll.setParticipants(new HashSet<PollParticipant>());
    		
    		// set items on poll
    		Set<PollItem> items = new HashSet<PollItem>();
    		for (String item: this.items) {
        		PollItem pollItem = new PollItem();
        		pollItem.setText(item);
        		items.add(pollItem);
    		}
    		poll.setItems(items);
    		
    		// set participants on poll
    		Set<PollParticipant> participants = new HashSet<PollParticipant>();
    		for (String email: this.participants) {
    			PollParticipant pollParticipant = new PollParticipant();
    			pollParticipant.setEmail(email);
    			participants.add(pollParticipant);
    		}
    		poll.setParticipants(participants);
    		
    		intent = null;
    		
    		try {
        		//send information to system
				Poll newPoll = pollService.createPoll(ctxt, poll);
				PollCache.add(newPoll);
				Log.i(TAG, "Created poll with id="+newPoll.getId());
				intent = getIntent();
				intent.putExtra(CREATE_POLL_EXTRA, newPoll.getId());
				setResult(RESULT_OK, intent);
        		Log.d(TAG, "finished CreatePollActivity");
        		this.finish();
			} catch (Exception e) {
				Log.d(TAG, "caught exception creating user", e);
				ErrorDialogHelper.showErrorDialog(this, e.getMessage());
			}
    		break;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch(id) {
		case START_DATE_DIALOG_ID:
			DatePickerDialog.OnDateSetListener listener1 = new DatePickerDialog.OnDateSetListener() {
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					Log.d(TAG, "This is the view.getId() return value: " + view.getId());
					mStartYear = year;
					mStartMonth = monthOfYear;
					mStartDay = dayOfMonth;
					Log.d(TAG, "Listening to START_DATE_DIALOG_ID touch...");
					updateStartDate();
				}
			};
			DatePickerDialog mStartDatePicker = new DatePickerDialog(this, listener1, mStartYear, mStartMonth, mStartDay);
			return mStartDatePicker;
		case START_TIME_DIALOG_ID:
			TimePickerDialog.OnTimeSetListener listener2 = new TimePickerDialog.OnTimeSetListener() {
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					mStartHour = hourOfDay;
					mStartMinute = minute;
					updateStartTime();
				}
			};
			TimePickerDialog mStartTimePicker = new TimePickerDialog(this, listener2, mStartHour, mStartMinute, false);
			return mStartTimePicker;
		case END_TIME_DIALOG_ID:
			TimePickerDialog.OnTimeSetListener listener3 = new TimePickerDialog.OnTimeSetListener() {
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					mEndHour = hourOfDay;
					mEndMinute = minute;
					updateEndTime();
				}
			};
			return new TimePickerDialog(this, listener3, mEndHour, mEndMinute, false);
		case END_DATE_DIALOG_ID:
			DatePickerDialog.OnDateSetListener listener4 = new DatePickerDialog.OnDateSetListener() {
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					Log.d(TAG, "This is the view.getId() return value: " + view.getId());
					mEndYear = year;
					mEndMonth = monthOfYear;
					mEndDay = dayOfMonth;
					Log.d(TAG, "Listening to START_DATE_DIALOG_ID touch...");
					updateEndDate();
				}
			};
			return new DatePickerDialog(this, listener4, mEndYear, mEndMonth, mEndDay);
		}
		return null;
	}
	
	private void updateStartDate() {
		Log.d(TAG, "Updating start date...");
		Calendar c = Calendar.getInstance();
		c.set(mStartYear, mStartMonth, mStartDay);
		mStartDateTime = c.getTime();
		txtStartTimeAndDate.setText(mDateFormat.format(mStartDateTime));
		Log.d(TAG, "Showing time dialog...");
		showDialog(START_TIME_DIALOG_ID);
	}
	
	public void updateStartTime() {
		Calendar c = Calendar.getInstance();
		c.setTime(mStartDateTime);
		c.set(mStartYear, mStartMonth, mStartDay, mStartHour, mStartMinute, 0);
		mStartDateTime = c.getTime();
		txtStartTimeAndDate.setText(mDateFormat.format(mStartDateTime));
	}
	
	private void updateEndDate() {
		Calendar c = Calendar.getInstance();
		c.set(mEndYear, mEndMonth, mEndDay);
		mEndDateTime = c.getTime();
		showDialog(END_TIME_DIALOG_ID);
	}
	
	public void updateEndTime() {
		Calendar c = Calendar.getInstance();
		c.setTime(mEndDateTime);
		c.set(mEndYear, mEndMonth, mEndDay, mEndHour, mEndMinute, 0);
		mEndDateTime = c.getTime();
		txtEndTimeAndDate.setText(mDateFormat.format(mEndDateTime));
	}
}
